<template>
  <div>
    <el-form label-width="80px">
      <el-form-item size="mini" :label="attr.name" v-for="attr in attrsList" :key="attr.id">
        <el-checkbox-group size="mini" style="width: 100%" v-model="attr.checkedVals" @change="groupCheckedChange" :disabled=disableCheck>
          <el-checkbox border style="width:200px" v-for="attrVal in attr.attrVals" :label="attrVal.val" :key="attrVal.val"
                       :checked="attrVal.checked" @change="checked=>itemCheckedChange(checked, attrVal)">{{ attrVal.val }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <el-table
      border
      :data="skuList"
      style="width: 100%;margin:20px 0 "
      :row-class-name="tableRowClassName"
      @cell-click="tabClick"
    >
      <el-table-column
        label="序号"
        align="center"
        type="index"
        width="80">
      </el-table-column>
      <el-table-column
        v-for="(item, index) in specs"
        :key="index"
        :prop="item.name"
        :label="item.name"
      >
      </el-table-column>
      <el-table-column
        prop="stock"
        label="库存"
      >
        <template slot="header">
          <span>库存</span>
          <i class="el-icon-edit"></i>
        </template>
        <template slot-scope="scope">
            <span v-if="scope.row.index === tabClickIndex && tabClickProperty === 'stock'">
              <el-input type="Number" v-model="scope.row.stock" maxlength="300" placeholder="请输入库存" size="mini"
                        @blur="inputBlur" @keyup.enter.native="inputBlur" />
            </span>
          <span v-else>{{ scope.row.stock }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="supplyPrice"
        label="成本价"
      >
        <template slot="header">
          <span>成本价</span>
          <i class="el-icon-edit"></i>
        </template>
        <template slot-scope="scope">
            <span v-if="scope.row.index === tabClickIndex && tabClickProperty === 'supplyPrice'">
              <el-input type="Number" v-model="scope.row.supplyPrice" maxlength="300" placeholder="请输入成本价" size="mini"
                        @blur="inputBlurPrice(scope.$index, scope.row,scope.column)" @keyup.enter.native="inputBlurPrice(scope.$index, scope.row,scope.column)"/>
               <!--<el-input-number :controls="false" v-model="scope.row.price" placeholder="请输入折扣价" size="mini" :precision="2" @blur="inputBlur" @keyup.enter.native="inputBlur"></el-input-number>-->
            </span>
          <span v-else>{{ scope.row.supplyPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="marketPrice"
      >
        <template slot="header">
          <span>市场建议价</span>
          <i class="el-icon-edit"></i>
        </template>
        <template slot-scope="scope">
            <span v-if="scope.row.index === tabClickIndex && tabClickProperty === 'marketPrice'">
              <el-input type="Number" v-model="scope.row.marketPrice" maxlength="300" placeholder="请输入市场建议价" size="mini"
                        @blur="inputBlurPrice(scope.$index, scope.row,scope.column)" @keyup.enter.native="inputBlurPrice(scope.$index, scope.row,scope.column)" />
            </span>
          <span v-else>{{ scope.row.marketPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="rate" label="利润率">
        <template slot-scope="scope">
          {{ scope.row.rate | formatFloat }}
        </template>
      </el-table-column>
      <el-table-column prop="price" label="销售价">
        <template slot-scope="scope">
          {{ scope.row.price | formatInt }}
        </template>
      </el-table-column>
      <el-table-column
        prop="icon"
        label="图标">
        <template slot-scope="scope">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="function(res, file){return handleUploadSuccess(res, file, scope.$index)}"
            :headers="imgUploadHeaders"
          >
            <img v-if="scope.row.imageUrl" :src="scope.row.imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!--<uploader :file-list="scope.row.fileList" :limit-count="1" @remove-success="function(fileList){return handleRemove(fileList,scope.$index)}" @upload-success="function(fileList){return handleSuccess(fileList,scope.$index)}"></uploader>-->
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
// import Uploader from '../../common/Uploader'
import { CalcGoodsPrice } from '../../../network/goods'

export default {
  name: 'GoodsSpecsAttrPane',
  /* components: {
    Uploader
  }, */
  props: {
    attrsList: {
      type: Array,
      default () {
        return []
      }
    },
    hideUpload: {
      type: Boolean,
      default: false
    },
    disableCheck: {
      type: Boolean,
      default () {
        return false
      }
    }
  },
  filters: {
    formatFloat (value) {
      return value.toFixed(2)
    },
    formatInt (value) {
      return value.toFixed(0)
    }
  },
  data () {
    return {
      // checked: false,
      skuList: [],
      specs: [],
      tabClickIndex: null, // 点击的单元格
      tabClickProperty: '', // 当前点击的列名,
      uploadUrl: window.g.MEDIA_URL + '/upload',
      imgUploadHeaders: { // 上传图片控件的header
        Authorization: sessionStorage.getItem('token')
      }
    }
  },
  methods: {
    tableRowClassName ({ row, rowIndex }) {
      row.index = rowIndex
    },
    tabClick (row, column, cell, event) {
      switch (column.property) {
        case 'stock':
          this.tabClickIndex = row.index
          this.tabClickProperty = column.property
          break
        case 'supplyPrice':
          this.tabClickIndex = row.index
          this.tabClickProperty = column.property
          break
        case 'marketPrice':
          this.tabClickIndex = row.index
          this.tabClickProperty = column.property
          break
        default:
          this.tabClickIndex = null
          this.tabClickProperty = ''
          break
      }
    },
    // 失去焦点初始化
    inputBlur () {
      this.tabClickIndex = null
      this.tabClickProperty = ''
    },
    inputBlurPrice (index, row, column) {
      this.tabClickIndex = null
      this.tabClickProperty = ''
      if (row.supplyPrice && row.marketPrice) {
        const marketPrice = Math.round(parseFloat(row.marketPrice) * Math.pow(10, 2)) / Math.pow(10, 2)
        const supplyPrice = Math.round(parseFloat(row.supplyPrice) * Math.pow(10, 2)) / Math.pow(10, 2)
        CalcGoodsPrice({ supplyPrice: supplyPrice, marketPrice: marketPrice }).then(res => {
          const result = res.data
          if (res.status !== 200) {
            // return this.alertMessage('获取信息失败2', 'error')
          }
          this.skuList[index].price = result.data.price
          this.skuList[index].rate = result.data.rate
        })
      }
      console.log('inputBlur index:', index, ';row:', row, ';column:', column)
    },
    itemCheckedChange (checked, attrVal) {
      // this.checked = !this.checked
      attrVal.checked = checked
      this.changeCheckedSpecs()
    },
    groupCheckedChange (val) {
      // console.log('----curl checked val:', val, ';---------------------list checkeds:', this.attrsList)
      // this.changeCheckedSpecs()
    },
    changeCheckedSpecs () {
      this.specs = []
      for (const item of this.attrsList) {
        if (item.checkedVals.length > 0) {
          this.specs.push({
            name: item.name,
            sortNum: item.sortNum,
            checked: item.checkedVals
          })
        }
      }
      // console.log('this selected specs length:', this.specs.length, ', attrlist length:', this.attrsList.length, ',specs:', this.specs)
      if (this.specs.length === this.attrsList.length) {
        this.computeSku()
      } else {
        this.skuList = []
      }
    },
    computeSku () {
      const specs = []
      for (const item of this.attrsList) {
        const attrSpecs = []
        for (const val of item.checkedVals) {
          attrSpecs.push({ value: val, attrId: item.id, name: item.name })
        }
        if (attrSpecs.length > 0) {
          specs.push(attrSpecs)
        }
      }
      const skuList = this.genSku(specs)
      console.log('---------compute skuList is:', skuList)
      const skus = []
      for (const sku of skuList) {
        const skuItem = this.genSkuItem(sku)
        skus.push(skuItem)
      }
      console.log('-----compute sku over:', skus)
      this.skuList = skus
    },
    genSkuItem (sku) {
      const dataItem = {}
      var key = ''
      for (const item of sku) {
        dataItem[item.name] = item.value
        key += '_' + item.value
      }
      dataItem.key = key
      const lastSku = this.skuList.find(item => item.key === key)
      if (lastSku) {
        dataItem.price = lastSku.price
        dataItem.oldPrice = lastSku.oldPrice
        dataItem.marketPrice = lastSku.marketPrice
        dataItem.supplyPrice = lastSku.supplyPrice
        dataItem.rate = lastSku.rate
        dataItem.stock = lastSku.stock
        dataItem.icon = lastSku.icon
        dataItem.fileList = lastSku.fileList
        dataItem.imageUrl = lastSku.imageUrl
      } else {
        dataItem.price = 0.00
        dataItem.oldPrice = 0.00
        dataItem.marketPrice = 0.00
        dataItem.supplyPrice = 0.00
        dataItem.rate = 0.00
        dataItem.stock = 0
        dataItem.icon = ''
        dataItem.fileList = []
        dataItem.imageUrl = ''
      }
      return dataItem
    },
    genSku (attrs) {
      return attrs.reduce((x, y) => {
        const arr = []
        x.forEach(x => y.forEach(y => arr.push(x.concat([y]))))
        return arr
      }, [[]])
    },
    handleRemove (fileList, index) {
      console.log('upload remove cur row sku:', this.skuList[index])
      this.skuList[index].icon = ''
    },
    handleSuccess (fileList, index) {
      console.log('upload succ cur row sku:', this.skuList[index])
      this.skuList[index].icon = fileList[0].mediaId
    },
    getSku () {
      const specsInfo = this.getSkuSpecs()
      if (!specsInfo.valid) {
        return { skuList: [], specs: {}, valid: false }
      }
      const skuListInfo = this.getSkuList()
      if (!skuListInfo.valid) {
        return { skuList: [], specs: {}, valid: false }
      }
      return { specs: specsInfo.specs, skuList: skuListInfo.skuList, valid: true }
    },
    getSkuSpecs () {
      if (this.specs.length < this.attrsList.length) {
        this.alertMessage('请选择所有规格', 'error')
        return {
          specs: {},
          valid: false
        }
      }
      const specs = {}
      const attrs = []
      this.specs.sort((a, b) => { return b.sortNum - a.sortNum })
      for (const spec of this.specs) {
        specs[spec.name] = spec.checked
        attrs.push(spec.name)
      }
      return {
        specs: {
          attrs: attrs,
          specs: specs
        },
        valid: true
      }
    },
    getSkuList () {
      const skuList = []
      for (const [idx, sku] of this.skuList.entries()) {
        /* if (sku.icon === '') {
          this.alertMessage('请上传商品规格的图标', 'error')
          return { skuList: [], valid: false }
        } */
        if (sku.marketPrice === '' || sku.supplyPrice === '' || sku.stock === '') {
          this.alertMessage('请将商品规格的原价、折扣价、库存填写完整', 'error')
          return { skuList: [], valid: false }
        }
        const marketPrice = Math.round(parseFloat(sku.marketPrice) * Math.pow(10, 2)) / Math.pow(10, 2)
        const supplyPrice = Math.round(parseFloat(sku.supplyPrice) * Math.pow(10, 2)) / Math.pow(10, 2)
        const stock = parseInt(sku.stock)
        if (marketPrice === 0 || supplyPrice === 0) {
          this.alertMessage('请将第' + (idx + 1) + '行商品的价格设置为非0值', 'error')
          return { skuList: [], valid: false }
        }
        const attrs = {}
        for (const spec of this.specs) {
          attrs[spec.name] = sku[spec.name]
        }
        const skuItem = {
          // price: price,
          // oldPrice: oldPrice,
          supplyPrice: supplyPrice,
          marketPrice: marketPrice,
          stock: stock,
          icon: sku.icon,
          attrs: attrs
        }
        console.log('this.spect:', this.specs, ', sku:', sku)
        skuList.push(skuItem)
      }
      return { skuList: skuList, valid: true }
    },
    resetSku () {
      this.skuList = []
    },
    handleUploadSuccess (res, file, index) {
      console.log('handleUploadSuccess res:', res, ';index:', index)
      // this.taskForm.icon = res.data.list[0].mediaId
      // this.imageUrl = window.g.MEDIA_DOWNLOAD_URL + this.taskForm.icon
      this.skuList[index].icon = res.data.list[0].mediaId
      this.skuList[index].imageUrl = window.g.MEDIA_DOWNLOAD_URL + res.data.list[0].mediaId
    }
  }
}
</script>

<style>
checkbox {
  margin-right: 30px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
